package com.lanxin.kh.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lanxin.kh.entity.KhContactrecord;
import com.lanxin.kh.entity.KhCustomercontact;
import com.lanxin.kh.entity.KhCustomerfavorite;
import com.lanxin.kh.entity.KhProduct;
import com.lanxin.kh.service.IKhContactrecordService;
import com.lanxin.kh.service.IKhCustomercontactService;
import com.lanxin.kh.service.IKhCustomerfavoriteService;
import com.lanxin.kh.service.IKhProductService;
import com.lanxin.kh.vo.KhContactrecordVO;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.stereotype.Controller;

import java.time.LocalDateTime;
import java.util.*;

@Controller
@RequestMapping("/favorite")
public class KhCustomerfavoriteController {

    private static final Logger logger = Logger.getLogger(KhCustomerfavoriteController.class);

    @Autowired
    private IKhCustomerfavoriteService customerfavoriteService;
    @Autowired
    private IKhProductService productService;
    @Autowired
    private IKhContactrecordService contactrecordService;
    @Autowired
    private IKhCustomercontactService customercontactService;


    // 分页查询客户关心产品列表（保持不变）
    @RequestMapping("/listKhCustomerfavorite")
    public String list(
            @RequestParam Integer customerid,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "5") Integer pageSize,
            Model model) {

        Page<KhCustomerfavorite> pageParam = new Page<>(page, pageSize);
        IPage<KhCustomerfavorite> pageResult = customerfavoriteService.page(
                pageParam,
                new QueryWrapper<KhCustomerfavorite>().eq("customerid", customerid)
        );

        for (KhCustomerfavorite favorite : pageResult.getRecords()) {
            KhProduct product = productService.getById(favorite.getProductid());
            if (product != null) {
                favorite.setProductName(product.getLinkname());
                favorite.setProductInfo(product.getInfo());
            }
        }

        List<KhProduct> products = productService.list(new QueryWrapper<KhProduct>().orderByAsc("oid"));
        List<KhCustomercontact> contacts = customercontactService.list(
                new QueryWrapper<KhCustomercontact>().eq("customerid", customerid)
        );

        model.addAttribute("pageResult", pageResult);
        model.addAttribute("products", products);
        model.addAttribute("contacts", contacts);
        model.addAttribute("customerid", customerid);

        return "kh/listKhCustomerfavorite";
    }


    // 添加/修改客户关心产品（优化日志与异常处理）
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) // 新增：异常回滚
    @RequestMapping("/editKhCustomerfavorite")
    public String edit(KhCustomerfavorite customerfavorite, Model model) {
        try {
            if (customerfavorite.getCustomerid() == null || customerfavorite.getProductid() == null) {
                logger.error("添加/修改失败：客户ID=" + customerfavorite.getCustomerid() + "，产品ID=" + customerfavorite.getProductid());
                model.addAttribute("alertMsg", "paramError");
                return "redirect:/favorite/listKhCustomerfavorite?customerid=" + customerfavorite.getCustomerid() + "&alertMsg=paramError";
            }

            // 新增场景防重复
            if (customerfavorite.getOid() == null) {
                long repeatCount = customerfavoriteService.count(
                        new QueryWrapper<KhCustomerfavorite>()
                                .eq("customerid", customerfavorite.getCustomerid())
                                .eq("productid", customerfavorite.getProductid())
                );
                if (repeatCount > 0) {
                    logger.warn("添加重复：客户ID=" + customerfavorite.getCustomerid() + "，产品ID=" + customerfavorite.getProductid());
                    return "redirect:/favorite/listKhCustomerfavorite?customerid=" + customerfavorite.getCustomerid() + "&alertMsg=repeat";
                }
            }

            boolean isSuccess = customerfavoriteService.saveOrUpdate(customerfavorite);
            if (!isSuccess) {
                logger.error("操作失败：客户ID=" + customerfavorite.getCustomerid() + "，产品ID=" + customerfavorite.getProductid());
                model.addAttribute("alertMsg", "operateFail");
            }
        } catch (Exception e) {
            // 新增：捕获所有异常，避免事务未回滚
            logger.error("添加/修改客户关心产品异常", e);
            model.addAttribute("alertMsg", "operateFail");
        }

        return "redirect:/favorite/listKhCustomerfavorite?customerid=" + customerfavorite.getCustomerid();
    }


    // 添加客户跟踪记录（保持不变）
    @Transactional(propagation = Propagation.REQUIRED)
    @RequestMapping("/addKhContactrecord")
    public String addContactrecord(KhContactrecord contactrecord, Model model) {
        if (contactrecord.getFavoriteid() == null || contactrecord.getEmpid() == null
                || StringUtils.isEmpty(contactrecord.getReason())
                || StringUtils.isEmpty(contactrecord.getResult())) {
            logger.error("添加跟踪记录失败：参数不完整，favoriteID=" + contactrecord.getFavoriteid());
            KhCustomerfavorite favorite = customerfavoriteService.getById(contactrecord.getFavoriteid());
            return "redirect:/favorite/listKhCustomerfavorite?customerid=" + (favorite != null ? favorite.getCustomerid() : "") + "&alertMsg=paramError";
        }

        // 若字段是 LocalDateTime 类型，替换为：
         contactrecord.setContactDate(LocalDateTime.now());

        boolean isSuccess = contactrecordService.save(contactrecord);
        if (!isSuccess) {
            logger.error("添加跟踪记录失败：favoriteID=" + contactrecord.getFavoriteid());
        }

        KhCustomerfavorite favorite = customerfavoriteService.getById(contactrecord.getFavoriteid());
        return "redirect:/favorite/listKhCustomerfavorite?customerid=" + favorite.getCustomerid();
    }


    // 删除客户关心产品（优化异常处理与日志）
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @RequestMapping("/deleteKhCustomerfavorite")
    @ResponseBody
    public boolean delete(@RequestParam Integer oid) {
        try {
            // 1. 先检查关联的跟踪记录
            long recordCount = contactrecordService.count(
                    new QueryWrapper<KhContactrecord>().eq("favoriteid", oid)
            );
            if (recordCount > 0) {
                logger.warn("删除失败：存在跟踪记录，oid=" + oid);
                return false; // 有关联记录，返回false
            }

            // 2. 执行删除
            boolean isDeleted = customerfavoriteService.removeById(oid);
            if (isDeleted) {
                logger.info("删除成功：oid=" + oid);
                return true;
            } else {
                logger.error("删除失败：记录不存在，oid=" + oid);
                return false;
            }
        } catch (Exception e) {
            // 新增：捕获数据库异常（如外键约束）
            logger.error("删除客户关心产品异常，oid=" + oid, e);
            return false;
        }
    }


    // 前端重复校验接口（优化日志）
    @RequestMapping("/checkKhCustomerfavorite")
    @ResponseBody
    public Map<String, Boolean> checkRepeat(
            @RequestParam(required = false) Integer customerid,
            @RequestParam(required = false) Integer productid) {

        long count = customerfavoriteService.count(
                new QueryWrapper<KhCustomerfavorite>()
                        .eq("customerid", customerid)
                        .eq("productid", productid)
        );
        // 构造JSON对象（包含valid字段）
        Map<String, Boolean> result = new HashMap<>();
        result.put("valid", count == 0);
        return result;

    }


    // 跟踪记录列表（保持不变）
    @RequestMapping("/listKhContactrecord")
    public String listKhContactrecord(
            Model model,
            @RequestParam Integer favoriteid,
            @RequestParam Integer customerid,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "5") Integer pageSize
    ) {
        Page<KhContactrecord> pageParam = new Page<>(page, pageSize);
        IPage<KhContactrecord> contactPage = contactrecordService.page(
                pageParam,
                new QueryWrapper<KhContactrecord>().eq("favoriteid", favoriteid)
                        .orderByDesc("contactDate")
        );

        IPage<KhContactrecordVO> voPage = new Page<>();
        BeanUtils.copyProperties(contactPage, voPage);

        List<KhContactrecordVO> voList = new ArrayList<>();
        for (KhContactrecord contact : contactPage.getRecords()) {
            KhContactrecordVO vo = new KhContactrecordVO();
            BeanUtils.copyProperties(contact, vo);

            KhCustomercontact customerContact = customercontactService.getById(contact.getEmpid());
            if (customerContact != null) {
                vo.setEmpName(customerContact.getContactName());
            }

            voList.add(vo);
        }
        voPage.setRecords(voList);

        model.addAttribute("pageResult", voPage);
        model.addAttribute("favoriteid", favoriteid);
        model.addAttribute("customerid", customerid);

        return "kh/listKhContactrecord";
    }
}